{% load i18n %}
{% load staticfiles %}
<script type="text/javascript">
{% autoescape off %}
    var select_button_active = false;

    $('.modal-forms').css('max-height', '500px').css('overflow-y', 'scroll');
    $('.modal-cloose-btn').css('margin','20px');

    $('.modal-cloose-btn').click(function(){
      $('.modal-forms').modal('hide');
    });

    $('#id_resource-poc').change(function(){
      if($(this).val() === ''){
        $('#poc_form').modal();
      }
    });

    var metadata_uri = $(location).attr('pathname').split('/').pop();
    var metadata_update_done = false;
    var metadata_preview = false;
    var is_advanced = (metadata_uri.match(/metadata_advanced/i) != null);
    var is_category_mandatory = {% if TOPICCATEGORY_MANDATORY %}true{% else %}false{% endif %};
    var is_group_mandatory = {% if GROUP_MANDATORY_RESOURCES %}true{% else %}false{% endif %};

    var updateWizard = function() {
      var activeTab = $("#edit-metadata .wizard--progress li.is-active");
      var first = $("#edit-metadata .wizard--progress li:first-child");
      var last = $("#edit-metadata .wizard--progress li:last-child");
      var firstIndex= first && $(first[0]).data("step");
      var tabIndex = activeTab && $(activeTab[0]).data("step");
      var lastIndex = last && $(last[0]).data("step");

      // buttons visibility
      $('#btn_back_dwn').toggle(firstIndex !== tabIndex);
      $('#btn_next_dwn').toggle(lastIndex !== tabIndex);

      // wizard
      if (tabIndex >= 0) {
        var first;
        for (var i = 0; i < lastIndex; i++) {
          var nextTab = $("#edit-metadata .wizard--progress li[data-step=" + (i) + "]");
          if (nextTab) {
            if(i < tabIndex) {
              nextTab.toggleClass('is-complete', true);
            } else {
              nextTab.toggleClass('is-complete', false);
            }
          }
        }
      }
    }

    // done button tooltip variables
    var tooltipShown = false;
    var gotIt = false;
    var tooltipContent =  'All fields declared mandatory by the schema are completed, you can continue editing the optional fields or click on "Done" to save your changes and close this page. '
      + '<a id="close-popover-done" data-toggle="clickover" class="btn btn-small btn-primary pull-right">Got it</a><br/>';
    $('.metadata-edit-done').popover({
        placement: 'left',
        html: true,
        animation: true,
        content: tooltipContent
      });
    {% block completeness  %}
    var updateCompleteness = function(completeness) {
        {% block extendcompleteness %}{% endblock extendcompleteness %}
      $('#profileCompleteness .progress-bar').html(parseFloat(((completeness)*100).toFixed(0)) + ' %').width(parseFloat(((completeness)*100).toFixed(2)) + '%');
      $('#profileCompleteness .completed').toggle(completeness === 1);
      $('#profileCompleteness .not-completed').toggle(completeness !== 1);
      
      var mandatoryMissing = $('#mandatory').find('.input-empty:not([class^="select2"])').length > 0;
          if (mandatoryMissing) {
            var inputs = $('#mandatory').find('.input-empty:not([class^="select2"])');
            var empty = inputs.length;
            for (var i=0; i<inputs.length; i++) {
              if (typeof inputs[i].value !== undefined && inputs[i].value !== '') {
                empty--;
              }
            }
            mandatoryMissing = empty > 0;
          }
        var imgMissing = $('img#image').attr('src');
        if (imgMissing && imgMissing.includes('missing_thumb')) {
            mandatoryMissing = true
        }
      var advancedMissing = $('#advanced').find('.input-empty').length > 0;
          if (advancedMissing) {
            var inputs = $('#advanced').find('.input-empty');
            var empty = inputs.length;
            for (var i=0; i<inputs.length; i++) {
              if (typeof inputs[i].value !== undefined && inputs[i].value !== '') {
                empty--;
              }
            }
            advancedMissing = empty > 0;
          }

        {% if UI_REQUIRED_FIELDS %}
         var metadataMissing = $('#ownership').find('.input-empty').length > 0;
          if (metadataMissing) {
            var inputs = $('#ownership').find('.input-empty');
            var empty = inputs.length;
            for (var i=0; i<inputs.length; i++) {
              if (typeof inputs[i].value !== undefined && inputs[i].value !== '') {
                empty--;
              }
            }
            metadataMissing = empty > 0;
          }
          $('#completeness-hints .metadata-hint')
            .toggleClass('progress-bar-danger', metadataMissing)
            .toggleClass('progress-bar-success', !metadataMissing)
            .attr('title', metadataMissing ? gettext("some schema mandatory fields are missing") : gettext("Metadata Schema mandatory fields completed") )
            .tooltip('fixTitle');
        {% endif %}

      $('#completeness-hints .mandatory-hint')
        .toggleClass('progress-bar-danger', mandatoryMissing)
        .toggleClass('progress-bar-success', !mandatoryMissing)
        .attr('title', mandatoryMissing ? gettext("some schema mandatory fields are missing") : gettext("Metadata Schema mandatory fields completed") )
        .tooltip('fixTitle');
      $('#completeness-hints .advanced-hint')
        .toggleClass('progress-bar-danger', advancedMissing)
        .toggleClass('progress-bar-success', !advancedMissing)
        .attr('title', advancedMissing ? gettext("some schema mandatory fields are missing") : gettext("Metadata Schema mandatory fields completed") )
        .tooltip('fixTitle');
        //done button tooltip
        if(completeness === 1 && $('.metadata-edit-done').css('opacity')+"" === "0" && !tooltipShown && !gotIt) {
          tooltipShown = true;
          setTimeout(function() {
            $('.metadata-edit-done').popover('show');
            $(document).on('click', '#close-popover-done', function() {
                 $('.metadata-edit-done').popover('hide');
                 gotIt = true;
             });
          },1500);
        } else if (completeness < 1){
          tooltipShown = false;
          $('.metadata-edit-done').popover('hide');
        }
        // show/hide done button
        $('.metadata-edit-done').animate(completeness === 1 ? {width: '100px', opacity: 1} : {width: 0, opacity: 0});
    }
    {% endblock completeness  %}

    function getTab(number) {
      var activeTab = $("#edit-metadata .wizard--progress li.is-active");
      var tabIndex = activeTab && $(activeTab[0]).data("step");
      var nextTab = $("#edit-metadata .wizard--progress li[data-step=" + number + "]");
      if (nextTab) {
        activeTab.toggleClass('is-active');
        nextTab.tab('show');
        nextTab.toggleClass('is-active');
      }
      updateWizard();
    }

    function getPrevTab(){
      var activeTab = $("#edit-metadata .wizard--progress li.is-active");
      var tabIndex = activeTab && $(activeTab[0]).data("step");
      if (tabIndex >= 0) {
          getTab( tabIndex - 1 );
      }

    };

    function getNextTab(){
        var activeTab = $("#edit-metadata .wizard--progress li.is-active");
        var tabIndex = activeTab && $(activeTab[0]).data("step");
        if (tabIndex >= 0) {
            getTab( tabIndex + 1 );
        }
    };

    $(document).ready(
        function() {
          var pickerOptions = {
              //format: 'YYYY-MM-DD hh:mm:ss',
              format: 'YYYY-MM-DD HH:mm',
              icons: {
                  time: 'fa fa-clock-o',
                  date: 'fa fa-calendar',
                  up: 'fa fa-chevron-up',
                  down: 'fa fa-chevron-down'
              }
          };
    });

    $(document).ready(function() {
        $('.has-external-popover').each(function(){
                var help_text = $(this).attr("data-content");
                
                // Removes the second help icon from select2 fields
                if (help_text) {
                    var spanPopoverText = $('<span>', { class: 'external-popover', 'data-content': help_text  }).append("<strong><i class='fa fa fa-question-circle fa-1x'></i></strong>");
                    $(this)
                        .closest("div")
                        .children("span:not(.input-group):not(.select2)")  // Removes the second help icon for select2
                        .append(spanPopoverText);
            }});

        $('.external-popover').each(function(){
            $(this).popover({'trigger':'hover'});
        });

        $("#preview_image").show();
        $("#preview_map").hide();
        $("#set_thumbnail").hide();

        var changeTxt = ["Edit", "Close"];

        $("#change_thumbnail").click(function () {
            $(this).text(changeTxt.reverse()[0]);
            $("#preview_map, #preview_image").toggle(1000);
            $("#set_thumbnail").toggle();
            {% if layer_form %}
            $('#preview_image_src').attr('src', '{{ layer_form.thumbnail_url.value }}');
            {% elif map_form %}
            $('#preview_image_src').attr('src', '{{ map_form.thumbnail_url.value }}');
            {% endif %}
        });
    });

    $(document).ready(function() {
        var prevNum = 0, totalNum = 0;
        var empty = 0;
        {% block hints %}

        $('#completeness-hints .mandatory-hint').click(getTab.bind(null, 1));
        $('#completeness-hints .advanced-hint').click(getTab.bind(null, 2));
        {% endblock hints %}

        // set proper classes to count empty fields and display them
        var setInputEmpty = function( target, empty ) {
          if($(target).hasClass('value-select')) {
            // tkeywords
            // $(target).toggleClass("input-empty", empty);
            // $(target).parent().find('input.autocomplete').toggleClass("input-empty", empty);
          } else if( !$(target).hasClass('autocomplete') ){
            // display error status for token fields if not completed
            $(target).toggleClass("input-empty", empty);
            if (target.id.startsWith('id_tkeywords')) {
                $("#" + target.id).closest("p").toggleClass("has-error", empty);   
              }
          }
          var imgMissing = $('img#image').attr('src');
          if (imgMissing && !imgMissing.includes('missing_thumb')) {
              $('input#id_crop_file').removeClass("input-empty");
              $('input#id_crop_file').parent().find(".mandatory-warning").remove();
          }

          if(target.id === 'id_resource-keywords') {
            $(target).siblings('span').toggleClass('has-error', empty);
            $(target).toggleClass("input-empty", empty);
          }
        {% block target %}
          if(target.id === 'category_form' ||
             target.id === 'id_resource-regions' ||
             target.id === 'id_resource-group' || 
             target.id === 'id_resource-date' ||
             target.id === 'id_resource-links' || {{UI_REQUIRED_FIELDS}}.includes(target.id)
          ) {
              // group selector
              $(target).closest('#basicGroupInfo').toggleClass('has-error', empty);

              // category selector
              $(target).closest('#basicCategoryInfo').toggleClass('has-error', empty);
              $(target).closest('#req_item').toggleClass('has-error', empty);

              // regions container
              $(target).closest('#regions_multiselect_container').toggleClass('has-error', empty);
              $(target).toggleClass("input-empty", empty);
          }

        {% endblock target %}
          // bootstrap-select copies the select's classes, so it have to be removed
          if( $( '.bootstrap-select' ).hasClass("input-empty") ) {
            $( '.bootstrap-select' ).toggleClass("input-empty");
          }
        }

        //check if a field is mandatory
        var otherRestrictionsSelected  = function(e){
          var otherRestrictions = false
          try {
            idx = $('#id_resource-restriction_code_type')[0].selectedIndex;
            value = $('#id_resource-restriction_code_type')[0].options[idx].text;
            if(value === "otherRestrictions") {
                otherRestrictions = true;
            }
          } catch (err) {
              otherRestrictions = true;
          }
          return otherRestrictions;
        }

        var toggleRestrictionsConstraints = function(e){
          try {
            if(e && e.target &&
                    e.target.id == 'id_resource-constraints_other') {
              var ee = $('#id_resource-constraints_other')[0];
              if(otherRestrictionsSelected() && ee.value !== undefined && ee.value.trim() === '') {
                if(!$(ee).hasClass("input-empty")) {
                    setInputEmpty(ee, true);
                    $(ee).parent().append(gettext("<p class='xxs-font-size mandatory-warning'>&nbsp;&nbsp;&nbsp;<strong>{% trans "* Field declared Mandatory by the Metadata Schema" %}</strong></p>"));
                    empty++;
                } else {
                    setInputEmpty(ee, false);
                    $(ee).parent().find(".mandatory-warning").remove();
                    empty--;
                }
              }
             }
          } catch (err) {
            // Log error
            console.log(err);
            return false;
          }
          return true;
        }

        var isMandatoryField = function (el) {
          if(el.id.indexOf("resource-constraints") >= 0) {
            if(otherRestrictionsSelected()) {
                return true;
            }
            return false;
          }

          if (el.id.startsWith('id_tkeywords') && $(el).hasClass('treq')) {
              return true;
          } else if (el.id.startsWith('id_tkeywords') && !$(el).hasClass('treq')) {
              return false;
          }

          var is_mandatory = (el.id.indexOf("autocomplete") < 0 &&
                        (typeof $(el).attr("class") !== 'undefined' && $(el).attr("class").indexOf("select2") < 0) &&
                        !$(el).hasClass('value-select') &&
                        el.type !== 'radio' &&
                        el.type !== 'button');
            return is_mandatory;
        }
        
        {% block onInputChange %}
        var onInputChange = function(e){
            toggleRestrictionsConstraints(e);
            if(e.target.value !== undefined && e.target.value.trim() === ''){
                if(!$(e.target).hasClass("input-empty")){
                    if(isMandatoryField(this)) {
                        setInputEmpty(e.target, true);
                        var mandatoryWarning = "<p class='xxs-font-size mandatory-warning'>&nbsp;&nbsp;&nbsp;<strong>{% trans "* Field declared Mandatory by the Metadata Schema" %}</strong></p>"
                        if (!!$(this).closest('.date').length) {
                            $(e.target).parent().parent().append(gettext(mandatoryWarning));
                        } else if (!!$(this).closest('.check-select').length ) {
                            $(e.target).parent().parent().append(gettext(mandatoryWarning));
                        } else if (!!$(this).closest('#mdinfo').length || !!$(this).closest('#basicDescriptiveInfo').length || !!$(this).closest('#tadv_req').length || !!$(this).closest('#adv_req').length ) {
                            $(e.target).parent().append(gettext(mandatoryWarning));
                        }
                        empty++;
                    }
                }
            }
            else {
                if($(e.target).hasClass("input-empty")) {
                    if(isMandatoryField(this)) {
                        empty--;
                    }
                    setInputEmpty(e.target, false);
                    if (!!$(e.target).closest('.date').length) { 
                        $(e.target).parent().parent().find(".mandatory-warning").remove();
                    } else {
                        $(e.target).parent().find(".mandatory-warning").remove();
                    }
                    
                }
            }

            if(totalNum == prevNum) {
                try {
                    var perc = (totalNum <= 0 ? 0 : (totalNum-empty)/totalNum);
                        perc = (perc <= 1 ? perc : 1);
                    updateCompleteness(perc);
                } catch(err) {
                    // Log error
                    // console.log(err);
                }
            }
        };
        {% endblock onInputChange %}
        {% block trigger_onInputChange %}

        {{UI_REQUIRED_FIELDS}}.forEach(element => $('#' + element).change(onInputChange).change());

        $('#category_form').change(onInputChange).change();
        $('#id_resource-group').change(onInputChange).change();

        $('#id_resource-title').change(onInputChange).change();
        $('#id_resource-abstract').change(onInputChange).change();
        $('#id_resource-doi').change(onInputChange).change();
        $('#id_resource-attribution').change(onInputChange).change();
        $('#id_resource-data_quality_statement').change(onInputChange).change();
        $('#id_resource-restriction_code_type').change(onInputChange).change();

        $('#id_resource-date').change(onInputChange).change();
        $('#id_resource-links').change(onInputChange).change();

        var selection = document.querySelector('select[name="resource-keywords"]');
        if (selection  !== null) {
            selection.onchange=onInputChange
        }
        
        {{REQ_THESAURI}}.forEach(element => document.querySelector('select[name="'+ element + '"]').onchange=onInputChange);
        
        // workaround to trigger the change in advanced metadata editing
        // otherwise will remain not-required untill a change on the item
        for (item in {{REQ_THESAURI}}) {
            $("#id_" + {{REQ_THESAURI}}[item]).trigger("change");
        }

        $('#id_resource-regions').change(onInputChange).change();
        $('#id_resource-temporal_extent_end').on('blur', function() {$(this).change(onInputChange).change();})
        $('#id_resource-temporal_extent_start').on('blur', function() {$(this).change(onInputChange).change();})
        $('#mandatory').find(":input:not(.value-select):not(.autocomplete)").each(function(){
            if(isMandatoryField(this)) {
                prevNum++;
            }
            $('#category_form').on('rendered.bs.select', function() {
              $('.has-popover').popover({'trigger':'hover'});
            });

            $(this).change(onInputChange).change();

            if(isMandatoryField(this)){
                totalNum++;
            }
        });

        $('#mdinfo').find(":input:not(.value-select):not(.autocomplete)").each(function(){
            if(isMandatoryField(this)) {
                prevNum++;
            }

            $(this).change(onInputChange).change();

            if(isMandatoryField(this)){
                totalNum++;
            }
        });

        {% endblock trigger_onInputChange %}
        // Dataset attributes sorting
        $(document).ready(function() {
            //Helper function to keep table row from collapsing when being sorted
            var fixHelperModified = function(e, tr) {
                var $originals = tr.children();
                var $helper = tr.clone();
                $helper.children().each(function(index) {
                  $(this).width($originals.eq(index).width())
                });
                return $helper;
            };
            //Renumber table rows
            function renumber_table(tableID) {
                $(tableID + " input[name$=display_order]").each(function() {
                    //note: index 0 is for the header
                    count = $(this).closest('tr').index(tableID +' tr');
                    $(this).val(count);
                });
            }
            //Make table sortable
            $("#dataset tbody").sortable({
                items: "tr:not(.table-header)",
                helper: fixHelperModified,
                stop: function(event,ui) {renumber_table('#dataset table')}
            }).disableSelection();

            //change position on display_order field change
            $("#dataset table input[name$=display_order]").change(function(e) {
              if (e.originalEvent) {
                // user-triggered event
                var nextIndex = $( this ).val();
                if(nextIndex > 0) {
                  var to = $('#dataset tbody');
                  var currentPosition = $(this).closest('tr').index('#dataset tbody tr');
                  if(currentPosition > nextIndex) { nextIndex--; }
                  $(this).closest('tr').insertAfter(to.children().eq(nextIndex));
                }
                renumber_table('#dataset table')
              }
            });
        });

        $(".wizard--progress li").click(function(){
          $(this).tab('show');
          $(".wizard--progress li.is-active").toggleClass('is-active', false);
          $(this).toggleClass('is-active', true);
          updateWizard();
        });

        $('#btn_back_up').click(function(){getPrevTab()});
        $('#btn_back_dwn').click(function(){getPrevTab()});

        $('#btn_next_up').click(function(){getNextTab()});
        $('#btn_next_dwn').click(function(){getNextTab()});

        $('#btn_upd_md_up').click(function(){
            if
            ( is_category_mandatory &&
                (
                    (!is_advanced && $('#category_form').hasClass("input-empty")) ||
                    (is_advanced && !$('#category_form input:checked').val())
                )
            ) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                validateRequiredInput()
            }
        });

        $('#btn_upd_md_dwn').click(function(){
            if
            ( is_category_mandatory &&
                (
                    (!is_advanced && $('#category_form').hasClass("input-empty")) ||
                    (is_advanced && !$('#category_form input:checked').val())
                )
            ) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                validateRequiredInput()
            }
        });
        
        function validateRequiredInput() {
            var errors = ['{% trans "Following items are required:" %}']
            $( ':input[required]').each( function () {
                if ( this.value.trim() == '' ) {
                    errors.push(this.id)
                }
            });
            if (errors.length > 1) {
                console.error("Following items are required: " + errors)
                $(".general_errors").find("p").html(errors.join('<br>'));
                $('#error_mandatoryDialog').modal();
            } else {
                $('#preview_pleaseWaitDialog').modal();
            }
        }

        $('#btn_upd_md_done').click(function(){
            if
            ( is_category_mandatory &&
                (
                    (!is_advanced && $('#category_form').hasClass("input-empty")) ||
                    (is_advanced && !$('#category_form input:checked').val())
                )
            ) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                $('#preview_pleaseWaitDialog').modal();
                metadata_update_done = true;
                metadata_preview = false;
            }
        });

        $('#preview_tab').on('show.bs.tab', function(e){
            var errors = ['{% trans "Please, fill the following items before clicking on preview:" %}<br>']
                $( ':input[required]').each( function () {
                    if ( this.value.trim() == '' ) {
                        errors.push(this.id)
                    }
                });
            if (errors.length > 1) {
	                e.preventDefault();
                    console.error("Please, fill the following items before clicking on preview: " + errors)
                    $(".general_errors").find("p").html(errors.join('<br>'));
                    $('#error_mandatoryDialog').modal();
                } else if
            ( is_category_mandatory &&
                (
                    (!is_advanced && $('#category_form').hasClass("input-empty")) ||
                    (is_advanced && !$('#category_form input:checked').val())
                )
            ) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                $('#preview_pleaseWaitDialog').modal();
                try {
                    $('#preview_encoder_iframe')[0].style.width='100%';
                    $('#preview_encoder_iframe')[0].style.height='4500px';
                    metadata_preview = true;
                    $('#metadata_update').submit();

                    // buttons visibility
                    $('#btn_back_dwn').hide();
                    $('#btn_next_dwn').hide();
                    $('#btn_upd_md_dwn').hide();
                } catch(err) {
                    // Log error
                }
            }
        });

        $('#settings_tab').on('show.bs.tab', function() {
            // buttons visibility
            $('#btn_back_dwn').hide();
            $('#btn_next_dwn').hide();
            $('#btn_upd_md_dwn').show();
        });

        $('#metadata_edit_tab').on('show.bs.tab', function() {
          // buttons visibility
          $('#btn_upd_md_dwn').show();
          updateWizard();
        });

        $('#metadata_update').submit(function(e) {
            if
            ( is_category_mandatory &&
                (
                    (!is_advanced && $('#category_form').hasClass("input-empty")) ||
                    (is_advanced && !$('#category_form input:checked').val())
                )
            ) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                var formData = $(this).serializeArray();
                formData.forEach(function(entry) {
                    try{
                        if((typeof entry["name"]) === "string" &&
                            entry["name"].includes("keywords")) {
                            entry["value"] = escape(entry["value"]);
                        }
                        else if((typeof entry["name"]) !== "string" &&
                            entry["name"].contains("keywords")) {
                            entry["value"] = escape(entry["value"]);
                        }
                    }catch(err){
                        console.log(err);
                    }
                });

                // $.post('metadata', /*$(this).serialize()*/ $.param(formData))
                $.ajax({
                        url: "metadata",
                        type: "POST",
                        dataType: "JSON",
                        data: $.param(formData)
                   }).done(function(data){
                        // Do something more fancy with your respone
                        // $('.message').html(data.message);
                        if (!is_advanced) {
                            try {
                                $('#preview_encoder_iframe')[0].style.width='100%';
                                $('#preview_encoder_iframe')[0].style.height='100%';
                                $('#preview_encoder_iframe')[0].contentWindow.location.reload(true);
                            } catch(err) {
                                // Log error
                                console.log(err);
                            }
                        }
                        metadata_update_done = true;
                    }).fail(function(xhr, status, error) {
                        // error handling
                        // console.log(error);
                        try {
                            if(xhr.responseJSON && xhr.responseJSON['errors']) {
                                var errors = "<ul>";
                                for(error in xhr.responseJSON['errors']) {
                                    errors += "<li>" + error + ": " + xhr.responseJSON['errors'][error] + "</li>";
                                }
                                errors += "</ul>";
                                $("#preview_errorDialog .modal-body").html(errors);
                            } else {
                                if (xhr.responseText.indexOf('<!DOCTYPE html>') >= 0) {
                                    $("#preview_errorDialog .modal-body").html("Unknown Error Occurred.");
                                } else {
                                    $("#preview_errorDialog .modal-body").html(xhr.responseText);
                                }
                            }
                        } catch(err) {
                            if (xhr.responseText.indexOf('<!DOCTYPE html>') >= 0) {
                                $("#preview_errorDialog .modal-body").html(err);
                            } else {
                                $("#preview_errorDialog .modal-body").html(xhr.responseText);
                            }
                        }
                        $('#preview_errorDialog').modal();
                        metadata_update_done = false;
                    }).always(function (a, textStatus, b) {
                          $('#preview_pleaseWaitDialog').modal('hide');
                          if(textStatus === 'success' && metadata_update_done && !metadata_preview) {
                              if(new RegExp(".*/metadata$").test(e.target.action)) {
                                  window.location.replace(e.target.action.replace('/metadata',''));
                              } else if(new RegExp(".*/"+metadata_uri+"$").test(e.target.action)) {
                                  window.location.replace(e.target.action.replace('/'+metadata_uri,''));
                              }
                          }
                    });
            }
            e.preventDefault();
        });

        if(totalNum == prevNum) {
            try {
                var perc = (totalNum <= 0 ? 0 : (totalNum-empty)/totalNum);
                    perc = (perc <= 1 ? perc : 1);
                updateCompleteness(perc);
            } catch(err) {
                // Log error
                // console.log(err);
            }
        }
    });

    $('#id_resource-metadata_author').change(function(){
      if($(this).val() === ''){
        $('#metadata_form').modal();
      }
    });

    $(document).ready(function() {
      {% if layer.metadata_uploaded_preserve %}
        $('#metadata_update :input').attr('readonly','readonly');
      {% endif %}
        $('.has-popover').popover({'trigger':'hover'});

        /** 
        NOTE: This is commented as it needs updating to work with select2 and autocomlete light.
        
        var params = typeof FILTER_TYPE == 'undefined' ? {} : {'type': FILTER_TYPE};
        $.ajax({
            url: '/h_keywords_api',
            params: params,
            success: function(data) {
                data = JSON.parse(data)
                var kws = parseKeywords(data);
                {% if freetext_readonly %}
                    $('#id_resource-keywords').tokenfield({
                        createTokensOnBlur: true,
                        autocomplete: {
                            source: kws,
                            delay: 100
                        },
                        showAutocompleteOnFocus: true
                    }).on('tokenfield:createtoken', function (event) {
                        var exists = false;
                        $.each(kws, function(index, value) {
                            if (event.attrs.value === value) {
                                exists = true;
                            }
                        });
                        if(!exists) {
                            event.preventDefault(); //prevents creation of token
                        }
                        var existingTokens = $(this).tokenfield('getTokens');
                        $.each(existingTokens, function(index, token) {
                            if (token.value === event.attrs.value)
                                event.preventDefault();  //prevents creation of token
                        });
                    });
                    $('#id_resource-keywords').tokenfield('readonly');
                    $('div.token .close').click(function() {
                        const token_close_button = $(this);
                        const token_item = token_close_button.parent();
                        token_item.remove();
                        return false;
                    }); 
                {% else %}
                    $('#id_resource-keywords').tokenfield({
                        createTokensOnBlur: true,
                        autocomplete: {
                            source: kws,
                            delay: 100
                        },
                        showAutocompleteOnFocus: true
                    }).on('tokenfield:createtoken', function (event) {
                        var existingTokens = $(this).tokenfield('getTokens');
                        $.each(existingTokens, function(index, token) {
                            if (token.value === event.attrs.value)
                                event.preventDefault();  //prevents creation of token
                        });
                    });
                {% endif %}
                if (window.location.href.match('/metadata_advanced$')) {
                    if (!select_button_active) {
                        const select_button = $('<button id="id_freetext_keyword_select" class="btn btn-primary">Select</button>');
                        const select_button_parent = $('#id_resource-keywords').parent().parent();
                        select_button_parent.append(select_button);
                        select_button_active = true;
                    }
                    $('#id_freetext_keyword_select').click(function() {
                        $('#id_resource-keywords-tokenfield').blur().focus();
                    });
                    const resource_group = $('#id_resource-group');
                    resource_group.empty();
                    resource_group.append('<option value="">-----</option>');
                    {% for group in metadata_author_groups %}
                        {% if resource.group == group.group %}
                            resource_group.append(
                                '<option value="{{ group.group.id }}" selected="selected">{{ group.group.name }}</option>'
                            );
                        {% else %}
                            resource_group.append(
                                '<option value="{{ group.group.id }}">{{ group.group.name }}</option>'
                            );
                        {% endif %}
                    {% endfor %}
                }
                $('#treeview').treeview({
                    color: "#428bca",
                    expandIcon: "fa fa-folder",
                    collapseIcon: "fa fa-folder-open",
                    nodeIcon: "fa fa-tag",
                    showTags: true,
                    showIcon: true,
                    showCheckbox: false,
                    data: data,
                    levels: 1,
                    onNodeSelected: function($event, $data) {
                        var kws = $('#id_resource-keywords').tokenfield('getTokens');
                        var newToken = $data.text
                        var exists = false
                        for (var i=0; i<kws.length; i++) {
                            if (kws[i]['value'].indexOf(newToken) >=0) {
                                exists = true
                            }
                        }
                        if (!exists) {
                            $('#id_resource-keywords').tokenfield('createToken', $data.text);
                        }
                        // $('#treeview-toggle').click();
                    }
                });
                $('#treeview-toggle').click((e, value) => {
                $('#treeview').toggle();
                var icon = $(this).find('i');
                icon.toggleClass('fa-folder').toggleClass('fa-folder-open');
                });
            }
        }); */

        var parseKeywords = function(data) {
            var kws = [];
            for (kw in data) {
                if (data[kw] && data[kw].text) {
                    kws.push(data[kw].text);
                    if (data[kw].nodes) {
                        var kwcs = parseKeywords(data[kw].nodes);
                        for (kwc in kwcs) {
                            kws.push(kwcs[kwc]);
                        }
                    }
                }
            }
            return kws;
        };

    }); 
{% endautoescape %}
</script>